package com.hongxun.design.activitys;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.facebook.drawee.view.SimpleDraweeView;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.bean.ArticleFootBean;
import com.hongxun.design.bean.FootInvolBean;
import com.hongxun.design.bean.ProjectFootBean;
import com.hongxun.design.bean.ProjectFootYearBean;
import com.hongxun.design.bean.photopassbean.SystemTypeBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.interfaces.HeadSecond;
import com.hongxun.design.listeners.ListenerSet;
import com.hongxun.design.listeners.MClickListener;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyDecimalFormat;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.headandbottonpanel.HeadSecondControlPanel;
import com.hongxun.design.ui.statisticsmap.brokenline.BrokenLineView;
import com.hongxun.design.ui.statisticsmap.pieview.CircularView;
import com.hongxun.design.utils.CommonAdapter;
import com.hongxun.design.utils.DataUtil;
import com.hongxun.design.utils.DensityUtil;
import com.hongxun.design.utils.ViewHolder;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.httputil.HttpStringCodeTableUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.imageutil.UriUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;


/**
 * Created by zerdoor_pc on 2016/6/5.
 * 项目足迹
 */
public class ProjectFootPrintActivity extends BaseActivity implements HeadSecond, View.OnClickListener {
    public String titile = "我的足迹";
    //选项卡
    LinearLayout tab1, tab2;
    TextView projectstatistics, workstatistics;
    LinearLayout project_item;
    LinearLayout work_item, foot_prent;
    private int index = 2;

    private Handler stageNumByYearHandler;
    private Handler workStatisticsHandler;
    private Handler stageArticleFootHandler;

    List<ProjectFootYearBean> TimeData;
    ListView refreshListView;
    SwipeRefreshLayout listview_foot_ref;
    List<ArticleFootBean> beans;
    CommonAdapter adapter;
    BrokenLineView lineview;
    CircularView publish, num;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_projectfootprint);
        findBar();
        findView();
        initialization();
    }

    @Override
    public void findBar() {
        HeadSecondControlPanel bit_layout = (HeadSecondControlPanel) findViewById(R.id.details_layout);
        bit_layout.initHeadPanel(DataUtil.getsecondbean("", View.INVISIBLE, R.color.bar_right, ListenerSet.back, titile, R.color.title, View.VISIBLE, IconSourse.BACK + "", View.VISIBLE));

    }

    @Override
    protected void onResume() {
        MyApp.activity = this;
        mActivity = this;
        super.onResume();
    }


    @Override
    protected void findView() {
        super.findView();

        /**基础信息**/
        tab1 = (LinearLayout) findViewById(R.id.button_foot_projectstatistics);
        projectstatistics = (TextView) findViewById(R.id.foot_projectstatistics);
        project_item = (LinearLayout) findViewById(R.id.project_item);


        tab2 = (LinearLayout) findViewById(R.id.button_foot_workstatistics);
        workstatistics = (TextView) findViewById(R.id.foot_workstatistics);
        work_item = (LinearLayout) findViewById(R.id.work_item);

        foot_prent = (LinearLayout) findViewById(R.id.foot_prent);

        publish = (CircularView) findViewById(R.id.circularview_publish);
        num = (CircularView) findViewById(R.id.circularview_num);
        lineview = (BrokenLineView) findViewById(R.id.foot_brokenlineview);

        findWorkView();
        listview_foot_ref = (SwipeRefreshLayout) findViewById(R.id.listview_foot_ref);//数据控件
        refreshListView = (ListView) findViewById(R.id.listview_foot);//数据控件
        //refreshListView.setAdapter();
        listview_foot_ref.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (currYear.length() != 0) {
                    StageArticleFoot(currYear);
                } else {
                    listview_foot_ref.setRefreshing(false);
                }
            }
        });
        tab1.setOnClickListener(this);
        tab2.setOnClickListener(this);
    }

    TextView exp_mil, design_num, audit_num, manang_num;

    private void findWorkView() {
        exp_mil = (TextView) findViewById(R.id.foot1_value);//踏勘
        design_num = (TextView) findViewById(R.id.foot2_value);//设计
        audit_num = (TextView) findViewById(R.id.foot3_value);//审核
        manang_num = (TextView) findViewById(R.id.foot4_value);//负责
    }

    private void setValue(ProjectFootBean bean) {
        try {

            exp_mil.setText(MyDecimalFormat.getDouble(Double.parseDouble(text(bean.exp_mil)), "0.000"));
        } catch (Exception e) {
            exp_mil.setText("0.000");
        }
        design_num.setText(text(bean.design_num));
        audit_num.setText(text(bean.audit_num));
        manang_num.setText(text(bean.manang_num));
    }

    private String text(String s) {
        if (s == null || s.length() == 0) {
            s = "0";
        }
        return s;
    }

    @Override
    protected void initialization() {
        super.initialization();
        addStageNumByYearHandler();
        addWorkStatisticsHandler();
        addStageArticleFootHandler();
        stageNumByYear();//年统计
        WorkStatistics();//工作统计

        onClick(tab1);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_foot_projectstatistics://项目统计
                checkChange(tab1, projectstatistics, Constant.projectstatistics);
                break;
            case R.id.button_foot_workstatistics://工作统计
                checkChange(tab2, workstatistics, Constant.workstatistics);
                break;
        }
    }


    /**
     * 切换*
     */
    private void checkChange(View v, TextView words, int i) {
        if (index == i) return;
        clearStatus();
        v.setBackgroundResource(R.drawable.wihte_item);
        words.setTextColor(getResources().getColor(R.color.caikan_bule));
        if (i == Constant.projectstatistics) {
            project_item.setVisibility(View.VISIBLE);
            work_item.setVisibility(View.GONE);
        } else {
            project_item.setVisibility(View.GONE);
            work_item.setVisibility(View.VISIBLE);
        }
        index = i;


    }

    /**
     * 改变现象卡的选中状态
     */
    private void clearStatus() {
        if (index == Constant.projectstatistics) {
            tab1.setBackgroundResource(R.drawable.grayline_wihte_tabuncheck_item);
            projectstatistics.setTextColor(getResources().getColor(R.color.title));
        } else if (index == Constant.workstatistics) {
            tab2.setBackgroundResource(R.drawable.grayline_wihte_tabuncheck_item);
            workstatistics.setTextColor(getResources().getColor(R.color.title));
        }
    }

    /***************************************UI加载*****************************************************/
    /**
     * 加载年份*
     */
    List<TextView> views = new ArrayList<>();

    private void addViewTomLinearLayout(ProjectFootYearBean s) {
        MyLog.L(MString.SUCCESSED + " SystemTypeBean=" + JSON.toJSONString(s));
        RelativeLayout layout = new RelativeLayout(this);
        TextView view = new TextView(this);
        view.setText(" " + s.getX() + " ");
        view.setTextSize(16);
        view.setTextColor(getResources().getColor(R.color.gray));
        view.setGravity(Gravity.CENTER);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, DensityUtil.dip2px(this, 36));
        params.setMargins(10, 0, 0, 0);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        layout.addView(view, params);
        views.add(view);
        view.setOnClickListener(new MClickListener(0, s) {
            @Override
            public void onClick(View view, int position, Object msg) {
                if (views.size() > 0) {
                    for (TextView textView : views) {
                        textView.setBackground(null);
                    }
                }
                if (adapter != null) {
                    beans.clear();
                    stageArticleFootHandler.sendEmptyMessage(2);
                }

                view.setBackgroundResource(R.drawable.circular6_blue_line3);
                StageArticleFoot(((ProjectFootYearBean) msg).getX());
            }
        });
        final float scale = getResources().getDisplayMetrics().density;
        int left = (int) (10 * scale + 0.5f);
        layout.setPadding(left, 0, left, 0);
        foot_prent.addView(layout, RelativeLayout.LayoutParams.WRAP_CONTENT, foot_prent.getHeight() - 4);
    }

    /**
     * 折线图*
     */
    private void addLineGraph() {

        if (TimeData.size() > 0) {
            List<String> x_line = new ArrayList<>();
            List<Integer> y_publish = new ArrayList<>();
            List<Integer> y_stage = new ArrayList<>();

            List<ProjectFootYearBean> cop = new ArrayList<>();
            cop.addAll(TimeData);
            Collections.reverse(cop);
            for (ProjectFootYearBean p : cop) {
                x_line.add(p.getX());
                y_publish.add(Integer.parseInt(p.getY_publish()));
                y_stage.add(Integer.parseInt(p.getY_stage()));

            }

            lineview.setData(x_line, y_publish, y_stage);
            publish.setBackgroundColor(lineview.getcolor(0));
            num.setBackgroundColor(lineview.getcolor(1));
        }

    }
    /**
     * ******************************数据请求********************************************************
     */

    /**
     * 年统计项目数*
     */
    private void stageNumByYear() {
        MyApp.HTTP.stageNumByYear(stageNumByYearHandler, HttpStringUtil.SUCCESSED);
    }

    /**
     * 年统计项目数handler*
     */
    private void addStageNumByYearHandler() {
        stageNumByYearHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (TimeData == null) {
                                TimeData = FastJsonUtil.getProjectFoot_Year((String) msg.obj);
                            } else {
                                TimeData.clear();
                                TimeData.addAll(FastJsonUtil.getProjectFoot_Year((String) msg.obj));
                            }
                            stageNumByYearHandler.sendEmptyMessage(1);
                            stageNumByYearHandler.sendEmptyMessage(2);
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 1:
                        if (TimeData != null) {
                            for (ProjectFootYearBean s : TimeData) {
                                addViewTomLinearLayout(s);
                            }
                            if (views.size() > 1) {
                                views.get(0).callOnClick();
                            }
                        }

                        break;
                    case 2:
                        //加载折线图
                        addLineGraph();
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }


    /**
     * 工作统计*
     */
    private void WorkStatistics() {
        MyApp.HTTP.WorkStatistics(workStatisticsHandler, HttpStringUtil.SUCCESSED);
    }

    /**
     * 工作统计handler*
     */
    private void addWorkStatisticsHandler() {
        workStatisticsHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            setValue(FastJsonUtil.getProjectFoot_info((String) msg.obj));
                        } else {
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }


    /**
     * 统计阶段和文章*
     */
    private String currYear = "";

    private void StageArticleFoot(String year) {
        this.currYear = year;
        showWaitDialog(-1);
        MyApp.HTTP.StageArticleFoot(stageArticleFootHandler, HttpStringUtil.SUCCESSED, year);
    }

    /**
     * 统计阶段和文章handler*
     */
    private void addStageArticleFootHandler() {
        stageArticleFootHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            com.alibaba.fastjson.JSONObject object = JSON.parseObject((String) msg.obj);
                            Set<String> KEY = object.keySet();
                            Object[] keys = KEY.toArray();
                            if (beans == null) {
                                beans = new ArrayList<>();
                            } else {
                                beans.clear();
                            }
                            for (int i = 12; i >= 1; i--) {
                                try {
                                    ArticleFootBean bean = FastJsonUtil.getProjectFoot_(object.getString(i + ""));
                                    if (!(bean.getInvol().size() == 0 && bean.getFinish().size() == 0 && bean.getPublish().size() == 0)) {
                                        bean.setMonth(i + "");
                                        beans.add(bean);
                                    }

                                } catch (Exception e) {
                                }
                            }
                            stageArticleFootHandler.sendEmptyMessage(1);
                        } else {
                            hideWaitIngDialog();
                            listview_foot_ref.setRefreshing(false);
                            ToastShow.showShort(mActivity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case 2:

                        setListview();
                        break;
                    case 1:
                        setListview();
                        stageArticleFootHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stageArticleFootHandler.sendEmptyMessage(3);
                            }
                        },1000);

                        break;
                    case 3:
                        hideWaitIngDialog();
                        break;
                    case HttpStringUtil.ERROR:
                        hideWaitIngDialog();
                        listview_foot_ref.setRefreshing(false);
                        ToastShow.showShort(mActivity, (String) msg.obj);
                        break;
                }
            }
        };
    }


    private void setListview(){
        if (adapter == null) {
            adapter = new CommonAdapter<ArticleFootBean>(mActivity, R.layout.listview_item_foot_article) {
                @Override
                public void convert(ViewHolder viewHolder, ArticleFootBean bean) {
                    TextView foot_month = viewHolder.getView(R.id.foot_month);
                    TextView invol_words = viewHolder.getView(R.id.foot_invol_words);
                    TextView finish_words = viewHolder.getView(R.id.foot_finish_words);
                    TextView publish_words = viewHolder.getView(R.id.foot_publish_words);
                    LinearLayout invollist = viewHolder.getView(R.id.foot_invol_list);
                    LinearLayout finishlist = viewHolder.getView(R.id.foot_finish_list);
                    LinearLayout publishlist = viewHolder.getView(R.id.foot_publish_list);
                    View invol_line = viewHolder.getView(R.id.foot_invol_line);
                    View finish_line = viewHolder.getView(R.id.foot_finish_line);
                    View publish_line = viewHolder.getView(R.id.foot_publish_line);

                    try {
                        foot_month.setText(bean.getMonth());
                        invol_words.setText("参与阶段工作" + bean.getInvol().size() + "个");
                        finish_words.setText("完成阶段工作" + bean.getFinish().size() + "个");
                        publish_words.setText("发布文章" + bean.getPublish().size() + "篇");
                        if (bean.getInvol() == null || bean.getInvol().size() == 0) {
                            invollist.removeAllViews();
                            invollist.setVisibility(View.GONE);
                            invol_words.setVisibility(View.GONE);
                            invol_line.setVisibility(View.GONE);
                        } else {
                            invollist.setVisibility(View.VISIBLE);
                            invol_words.setVisibility(View.VISIBLE);
                            invol_line.setVisibility(View.VISIBLE);
                            addInvollist(bean.getInvol(), invollist);
                        }

                        if (bean.getFinish() == null || bean.getFinish().size() == 0) {
                            finishlist.removeAllViews();
                            finishlist.setVisibility(View.GONE);
                            finish_words.setVisibility(View.GONE);
                            finish_line.setVisibility(View.GONE);
                        } else {
                            finishlist.setVisibility(View.VISIBLE);
                            finish_words.setVisibility(View.VISIBLE);
                            finish_line.setVisibility(View.VISIBLE);
                            addInvollist(bean.getFinish(), finishlist);
                        }

                        if (bean.getPublish() == null || bean.getPublish().size() == 0) {
                            publishlist.removeAllViews();
                            publishlist.setVisibility(View.GONE);
                            publish_words.setVisibility(View.GONE);
                            publish_line.setVisibility(View.GONE);
                        } else {
                            publishlist.setVisibility(View.VISIBLE);
                            publish_words.setVisibility(View.VISIBLE);
                            publish_line.setVisibility(View.VISIBLE);
                            addInvollist(bean.getPublish(), publishlist);
                        }


                    } catch (Exception e) {
                    }

                }
            };
            refreshListView.setAdapter(adapter);
            adapter.setData(beans);
//                            adapter = new FootAdapter(mActivity, beans);
//                            refreshListView.setAdapter(adapter);
            MyLog.L(MString.SUCCESSED + "new");
            listview_foot_ref.setRefreshing(false);
        } else {
            adapter.setData(beans);
            listview_foot_ref.setRefreshing(false);
//                            refreshListView.update();
//                            refreshListView.setPosition(0);
            MyLog.L(MString.SUCCESSED + "Refresh");
        }
    }

    private void addInvollist(List<FootInvolBean> data, LinearLayout layout) {
        layout.removeAllViews();
        if (data == null || data.size() == 0) return;
        for (FootInvolBean bean : data) {
            addItem(bean, layout);
        }
    }

    private void addItem(FootInvolBean bean, LinearLayout layout) {
        View view = LayoutInflater.from(this).inflate(R.layout.listview_item_footinvol, null);

        SimpleDraweeView image = (SimpleDraweeView) view.findViewById(R.id.footinvol_image);
        TextView name = (TextView) view.findViewById(R.id.footinvol_name);
        TextView type = (TextView) view.findViewById(R.id.footinvol_type);
        TextView time = (TextView) view.findViewById(R.id.footinvol_time);
        TextView work = (TextView) view.findViewById(R.id.footinvol_work);
        try {
            time.setText(bean.mon1);
            if (bean.in_work != null) {
                name.setText(bean.p_name);
                image.setImageURI(UriUtil.getUri(bean.p_thumb));
                work.setVisibility(View.VISIBLE);
                if (bean.p_type != null && bean.p_type.length() > 0) {
                    type.setText(getProjectType(bean.p_type) + "项目");
                    type.setVisibility(View.VISIBLE);
                } else {
                    type.setVisibility(View.GONE);
                }

                work.setText("参与工作：" + bean.in_work);

            } else {
                name.setText(bean.title);
                image.setImageURI(UriUtil.getUri(bean.article_thumb));
                type.setVisibility(View.GONE);
                work.setVisibility(View.GONE);
            }

        } catch (Exception e) {
        }

        layout.addView(view);
    }

    List<SystemTypeBean> projectType;

    private String getProjectType(String code) {
        if (projectType == null)
            projectType = FastJsonUtil.JsonToData_Code(HttpStringCodeTableUtil.projectType);//项目类型
        for (SystemTypeBean s : projectType) {
            if (s.getTypecode().equals(code)) {
                return s.getTypename();
            }
        }
        return "";
    }


}
